package com.example.permissionservice.service.impl;

import com.example.permissionservice.entity.Role;
import com.example.permissionservice.entity.UserRole;
import com.example.permissionservice.mapper.RoleMapper;
import com.example.permissionservice.mapper.UserRoleMapper;
import com.example.permissionservice.service.PermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class PermissionServiceImpl implements PermissionService {

    private final UserRoleMapper userRoleMapper;
    private final RoleMapper roleMapper;

    private static final String ROLE_USER = "user";
    private static final String ROLE_ADMIN = "admin";

    /**
     * 为用户绑定指定角色
     * @param userId 用户ID
     * @param roleCode 角色代码
     */
    @Override
    @Transactional
    public void bindRole(Long userId, String roleCode) {
        userRoleMapper.findByUserId(userId).ifPresent(userRole -> {
            throw new IllegalStateException("用户 " + userId + " 已绑定角色，无法重复操作。");
        });

        Role role = getRoleByCode(roleCode);
        UserRole newUserRole = new UserRole(null, userId, role.getRoleId());
        userRoleMapper.save(newUserRole);
    }

    /**
     * 为新用户绑定默认角色（普通用户）
     * @param userId 用户ID
     */
    @Override
    @Transactional
    public void bindDefaultRole(Long userId) {
        userRoleMapper.findByUserId(userId).ifPresent(userRole -> {
            throw new IllegalStateException("用户 " + userId + " 已绑定角色，无法重复操作。");
        });

        Role userRoleEntity = getRoleByCode(ROLE_USER);
        UserRole newUserRole = new UserRole(null, userId, userRoleEntity.getRoleId());
        userRoleMapper.save(newUserRole);
    }

    /**
     * 查询用户角色代码
     * @param userId 用户ID
     * @return 角色代码 (e.g., "admin")
     */
    @Override
    public String getUserRoleCode(Long userId) {
        return userRoleMapper.findByUserId(userId)
                .map(UserRole::getRoleId)
                .flatMap(roleMapper::findById)
                .map(Role::getRoleCode)
                .orElse(null);
    }

    /**
     * 升级用户为管理员
     * @param userId 用户ID
     */
    @Override
    @Transactional
    public void upgradeToAdmin(Long userId) {
        updateUserRole(userId, ROLE_ADMIN);
    }

    /**
     * 降级用户为普通用户
     * @param userId 用户ID
     */
    @Override
    @Transactional
    public void downgradeToUser(Long userId) {
        updateUserRole(userId, ROLE_USER);
    }

    private void updateUserRole(Long userId, String roleCode) {
        UserRole userRole = userRoleMapper.findByUserId(userId)
                .orElseThrow(() -> new IllegalStateException("用户 " + userId + " 没有角色可以更新。"));
        
        Role targetRole = getRoleByCode(roleCode);
        userRole.setRoleId(targetRole.getRoleId());
        userRoleMapper.update(userRole);
    }

    private Role getRoleByCode(String roleCode) {
        return roleMapper.findByRoleCode(roleCode)
                .orElseThrow(() -> new IllegalStateException("角色 " + roleCode + " 在数据库中未找到。"));
    }
} 